# -*- coding: utf-8 -*-
import base64
import json

import requests
from Crypto.Cipher import AES
from django.conf import settings
from pyDes import des, CBC, PAD_PKCS5

from common.cache import redis_cache
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)


# AES加密（AES/ECB/PKCS7Padding）
def Encrypt_AES_ECB_PKCS7Padding(key, toEncrypt):
    toEncrypt = toEncrypt.encode("utf8")  # 转换为UTF8编码
    key = key.encode("utf8")
    bs = AES.block_size
    pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)  # PKS7
    cipher = AES.new(key, AES.MODE_ECB)  # ECB模式
    resData = cipher.encrypt(pad(toEncrypt))
    return base64.b64encode(resData)


# AES解密（AES/ECB/PKCS7Padding）
def Decrypt_AES_ECB_PKCS7Padding(key, encrData):
    encrData = base64.b64decode(encrData.encode("ascii"), ' /')
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]
    cipher = AES.new(key, AES.MODE_ECB)
    decrData = unpad(cipher.decrypt(encrData))
    return decrData.decode('utf-8')


# POST html表单提交
def build_form_post(params, gateway, pay_id, file_name):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    _LOGGER.info("%s create html: %s", file_name, html)
    cache_id = redis_cache.save_html(pay_id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# html表单提交
def build_form(params, gateway, pay_id, file_name, method):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='" + \
           method + "'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    _LOGGER.info("%s create html: %s", file_name, html)
    cache_id = redis_cache.save_html(pay_id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# request form
def requests_form(url, parameter_dict, file_name):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("%s create response: %s", file_name, response.text)
    return response


# requests json
def requests_json(url, parameter_dict, file_name):
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(url, data=json.dumps(parameter_dict), headers=headers, timeout=3, verify=False)
    _LOGGER.info("%s create response: %s", file_name, response.text)
    return response


# 获取字符串
def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start) + 3: p2 - 3]
    else:
        return ''


def des_encrypt(s, key):
    """
    DES 加密
    :param s: 原始字符串
    :return: 加密后字符串，16进制
    """
    secret_key = key
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(s, padmode=PAD_PKCS5)
    return base64.b64encode(en)
